package com.ruoyi.pac4j;

import cc.renzhihao.sso.config.IamConfig;
import com.ruoyi.system.domain.SysAuth;
import com.ruoyi.system.domain.SysKeystore;
import com.ruoyi.system.service.ISysAuthService;
import com.ruoyi.system.service.ISysKeystoreService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author renzhihao
 * @date 2023/10/16 16:14
 */
@Component
public class Pac4jSqlInitializingBean implements InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(Pac4jSqlInitializingBean.class);

    @Value("${ruoyi.server-name:http://127.0.0.1:9000}")
    private String serverName;

    @Autowired
    private ISysAuthService authService;

    @Autowired
    private ISysKeystoreService keystoreService;

    @Autowired
    private IamConfig iamConfig;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("加载sql");

        List<SysAuth> sysAuths = authService.selectAuthList(null);

        SysKeystore search = new SysKeystore();
        search.setInitial(0);
        List<SysKeystore> keystores = keystoreService.selectKeystoreList(search);

        SysKeystore keystore = null;
        if (CollectionUtils.isNotEmpty(keystores)) {
            keystore = keystores.get(0);
        }

        if (CollectionUtils.isNotEmpty(sysAuths)) {
            return;
        }

        String defaultAuthUrl = iamConfig.getCasServer();
        String defaultLogoutUrl = iamConfig.getCentralLogout().getDefaultUrl();

        String localServer = serverName;
        String successRedirectUrl = "/centralLogin";
        String callbackUrl = "/callback";

        SysAuth casAuth = new SysAuth();
        casAuth.setAuthName("CAS认证（默认）");
        casAuth.setInitial(0);
        casAuth.setLogoutUrl(defaultLogoutUrl);
        casAuth.setStatus(0);
        casAuth.setSort(1L);
        casAuth.setType("CAS");
        casAuth.setAuthUrl(defaultAuthUrl);
        casAuth.setClientName("cas_ry");
        casAuth.setLocalServer(localServer);
        casAuth.setSuccessRedirectUrl(successRedirectUrl);
        casAuth.setCallbackUrl(callbackUrl);
        casAuth.setCreateBy("admin");
        authService.insertAuth(casAuth);

        SysAuth jwtAuth = new SysAuth();
        jwtAuth.setAuthName("JWT认证（默认）");
        jwtAuth.setInitial(0);
        jwtAuth.setLogoutUrl(defaultLogoutUrl);
        jwtAuth.setStatus(0);
        jwtAuth.setSort(2L);
        jwtAuth.setType("JWT");
        jwtAuth.setAuthUrl(defaultAuthUrl);
        jwtAuth.setClientName("jwt_ry");
        jwtAuth.setLocalServer(localServer);
        jwtAuth.setSuccessRedirectUrl(successRedirectUrl);
        jwtAuth.setCallbackUrl(callbackUrl);
        jwtAuth.setEncryptionKey("SCohMtxkDqIt8v0VR5FVK2g8CT8DlxYy7cXO43ypMJo");
        jwtAuth.setSignatureKey("4Qy93T0Cea_s5J1IM8d_NZknAKVka_d7p_Inkm1WMckboJWBbte9JuxuUIaYgUg72WDwYhwGrqWKeW1ba6OVVQ");
        jwtAuth.setCreateBy("admin");
        authService.insertAuth(jwtAuth);

        SysAuth oauthAuth = new SysAuth();
        oauthAuth.setAuthName("OAUTH认证（默认）");
        oauthAuth.setInitial(0);
        oauthAuth.setLogoutUrl(defaultLogoutUrl);
        oauthAuth.setStatus(0);
        oauthAuth.setSort(3L);
        oauthAuth.setType("OAUTH2");
        oauthAuth.setAuthUrl(defaultAuthUrl + "/oauth2.0");
        oauthAuth.setScope("read");
        oauthAuth.setClientName("oauth_ry");
        oauthAuth.setClientId("oauth_ry");
        oauthAuth.setClientSecret("oauth_ry_secret");
        oauthAuth.setLocalServer(localServer);
        oauthAuth.setSuccessRedirectUrl(successRedirectUrl);
        oauthAuth.setCallbackUrl(callbackUrl);
        oauthAuth.setCreateBy("admin");
        authService.insertAuth(oauthAuth);

        SysAuth oidcAuth = new SysAuth();
        oidcAuth.setInitial(0);
        oidcAuth.setAuthName("OIDC认证（默认）");
        oidcAuth.setLogoutUrl(defaultLogoutUrl);
        oidcAuth.setStatus(0);
        oidcAuth.setSort(4L);
        oidcAuth.setType("OIDC");
        oidcAuth.setAuthUrl(defaultAuthUrl);
        oidcAuth.setClientName("oidc_ry");
        oidcAuth.setClientId("oidc_ry");
        oidcAuth.setScope("openid,st");
        oidcAuth.setWellKnown(defaultAuthUrl + "/oidc/.well-known");
        oidcAuth.setClientSecret("oidc_ry_secret");
        oidcAuth.setLocalServer(localServer);
        oidcAuth.setSuccessRedirectUrl(successRedirectUrl);
        oidcAuth.setCallbackUrl(callbackUrl);
        oidcAuth.setCreateBy("admin");
        authService.insertAuth(oidcAuth);

        SysAuth samlAuth = new SysAuth();
        samlAuth.setAuthName("SAML认证（默认）");
        samlAuth.setInitial(0);
        samlAuth.setLogoutUrl(defaultLogoutUrl);
        samlAuth.setStatus(0);
        samlAuth.setSort(5L);
        samlAuth.setType("SAML");
        samlAuth.setAuthUrl(defaultAuthUrl);
        samlAuth.setClientName("saml_ry");
        samlAuth.setLocalServer(localServer);
        samlAuth.setSuccessRedirectUrl(successRedirectUrl);
        samlAuth.setCallbackUrl(callbackUrl);
        samlAuth.setEntityId("saml_ry");
        samlAuth.setMetadataPath(defaultAuthUrl + "/idp/metadata");
        samlAuth.setMetadataFilename("sp-metadata_" + samlAuth.getEntityId() + ".xml");
        samlAuth.setAllSignatureValidationDisabled("Y");
        samlAuth.setAuthnRequestSigned("Y");
        samlAuth.setSpLogoutRequestSigned("Y");
        samlAuth.setWantsAssertionsSigned("N");
        samlAuth.setWantsResponsesSigned("Y");

        if (keystore != null) {
            samlAuth.setKeystoreId(keystore.getKeystoreId());
        }

        samlAuth.setCreateBy("admin");
        authService.insertAuth(samlAuth);

        SysAuth genOauthAuth = new SysAuth();
        genOauthAuth.setAuthName("通用OAUTH2认证（默认）");
        genOauthAuth.setInitial(0);
        genOauthAuth.setLogoutUrl(defaultLogoutUrl);
        genOauthAuth.setStatus(0);
        genOauthAuth.setSort(6L);
        genOauthAuth.setType("GENERIC_OAUTH2");
        genOauthAuth.setAuthUrl("http://127.0.0.1:8100/cas/oauth2.0/authorize");
        genOauthAuth.setTokenUrl("http://127.0.0.1:8401/oauth/token");
        genOauthAuth.setProfileUrl("http://127.0.0.1:8401/api/bff/v1.2/oauth2/userinfo");
        genOauthAuth.setProfilePath("data");
        genOauthAuth.setProfileVerb("GET");
        genOauthAuth.setScope("read");
        genOauthAuth.setProfileId("username");
        genOauthAuth.setClientName("generic_oauth_ry");
        genOauthAuth.setClientId("generic_oauth_ry");
        genOauthAuth.setClientSecret("generic_oauth_ry_secret");
        genOauthAuth.setTokenParamPosition("param");
        genOauthAuth.setLocalServer(localServer);
        genOauthAuth.setSuccessRedirectUrl(successRedirectUrl);
        genOauthAuth.setCallbackUrl(callbackUrl);
        genOauthAuth.setCreateBy("admin");
        authService.insertAuth(genOauthAuth);
    }
}
